import { Component, OnInit, Output, EventEmitter, Input, OnDestroy } from '@angular/core';
import { DialogService } from 'app/shared/dialog';
// import { NotificationService } from 'app/shared/service';
import { NzMessageService } from 'ng-zorro-antd';
import { ScheduledService } from '../scheduled.service';
import { FormGroup } from '@angular/forms';
import { EventCate } from '../scheduled-event.interface';
import { PublicService } from 'app/public/public.service';
import { SELECT_OPTIONS, SYSTEM_EVENT } from 'app/app.constants';
import * as moment from 'moment';
import { BullySubjectService } from 'app/shared/service';
import { AuthService } from 'app/auth/auth.service';
import { SystemService } from 'app/service/system.service';
import { filter } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'itmp-ir-record-list',
    templateUrl: './ir-record-list.component.html',
    styleUrls: ['./ir-record-list.component.css']
})
export class IrRecordListComponent implements OnInit, OnDestroy {
    @Output() changeTabPage = new EventEmitter();
    @Output() isIrSelected = new EventEmitter();
    @Output() isCreate = new EventEmitter<boolean>();
    @Input() accessButton;
    private _eventData = [];
    statusData: Array<any>;

    @Input()
    set eventData(data: EventCate[]) {
        if (data && data.length > 0) {
            this._eventData = [...data];
        }
    }

    get eventData(): EventCate[] {
        return this._eventData;
    }

    statusList: any;
    // @Input()
    // set statusData(statusData: EventCate[]) {
    //     if (statusData && statusData.length > 0) {
    //         this._statusData = statusData.filter(item => {
    //             const has = item.category === 'EventStatus' && (item.value === '0' || item.value === '1');
    //             if (has) {
    //                 this.statusList.push(item.name);
    //             }
    //             return has;
    //         });
    //     }
    // }
    // get statusData(): EventCate[] {
    //     return this._statusData;
    // }
    validateForm: FormGroup;
    toolbarList = [
        { className: 'icon-dingwei' },
        { className: 'icon-CCTV' },
        { className: 'icon-dayinfuyin-' },
        { className: 'icon-xiazai' }
    ];
    irTypeSelect = null;
    selectedItem = null;
    isEditable = false;
    editingItem = null;
    renderHeader = null;
    dateRange = [];
    dateUpRange = [];
    queryStartTime = null;
    queryEndTime = null;
    queryUpStartTime = null;
    queryUpEndTime = null;
    id = null;
    zoneId = null;
    roadName = null;
    typeSelect = null;
    statusSelect = null;
    listOfData = [];
    zoneList = []; // header上的select zone
    lane_blockages = ['arrow-up.png', 'cross.png'];
    // statusList = ['Anticipated', 'Notified', 'Confirmed', 'In Progress', 'Over'];
    // typeList = ['', '', 'Road Works', '', 'Road Maintence'];
    typeList = ['', '', '', '', '', '', '', 'Road Work', 'Road Maintenance'];
    // typeOptions: any = [{ label: 'Road Works', value: '7' }, { label: 'Road Maintence', value: '48' }];
    // statusOptions: any = [
    //     { label: 'Anticipated', value: '0' },
    //     { label: 'Notified', value: '1' },
    //     // { label: 'Ready Start', value: '2' },
    //     // { label: 'Cancelled', value: '3' },
    //     { label: 'Invalid', value: '2' },
    //     { label: 'Executed', value: '3' }/*  */
    // ];
    // 分页数据的对象
    pagination = {
        totalEle: 25,
        currentPage: 1,
        currentSize: 10,
        pageSize: 10
    };
    queryData = null;
    showTable = false;
    isCancelForce = false;
    isForceCancelVisible = false; // 强制取消计划弹框
    subscription;

    constructor(
        private dialog: DialogService,
        private message: NzMessageService,
        private SEService: ScheduledService,
        private pub: PublicService,
        private bully: BullySubjectService,
        private authService: AuthService,
        private systemService: SystemService,
        private translate: TranslateService
    ) {}

    _getSelectionList() {
        const res = this.pub.getSelectOptionsList(SELECT_OPTIONS.EVENT_STATUS);
        this.statusData = res.data.filter(item => +item.value === 0 || +item.value === 1);
        this.statusList = res.object;
        this.showTable = true;
    }

    ngOnInit() {
        this._getSelectionList();
        this.renderHeader = [
            {
                name: 'Event ID',
                key: null,
                value: 'id',
                isChecked: true
            },
            {
                name: 'Event Type',
                key: null,
                value: 'type',
                isChecked: true
            },
            {
                name: 'Zone ID',
                key: null,
                value: 'zoneID',
                isChecked: true
            },
            {
                name: 'Road Name',
                key: null,
                value: 'roadName',
                isChecked: true
            },
            {
                name: 'Planned Start Date',
                key: null,
                value: 'plannedStartTime',
                isChecked: true
            },
            {
                name: 'Planned End Date',
                key: null,
                value: 'plannedEndTime',
                isChecked: true
            },
            {
                name: 'LaneBlockage',
                key: null,
                value: 'laneBlockage',
                isChecked: true
            },
            {
                name: 'Status',
                key: null,
                value: 'status',
                isChecked: true
            }
        ];

        this.zoneList = this.systemService.userZoneList;
        if (this.zoneList.length) {
            this.getData();
        }
        this.subscription = this.bully
            .getSubject()
            .pipe(filter(res => !!res))
            .subscribe(res => {
                if (res['type'] === SYSTEM_EVENT.ZONE_CHANGE_EVENT) {
                    this.zoneList = res['data'];
                    this.refresh();
                }
            });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }

    // 刷新
    refresh() {
        // this.queryStartTime = this.getTimeStamp();
        // this.queryEndTime = new Date().getTime();
        // this.queryUpStartTime = this.getTimeStamp();
        // this.queryUpEndTime = new Date().getTime();
        this.queryStartTime = null;
        this.queryEndTime = null;
        this.queryUpStartTime = null;
        this.queryStartTime = null;
        this.queryUpEndTime = null;
        this.id = null;
        this.zoneId = null;
        this.roadName = null;
        this.typeSelect = null;
        this.statusSelect = null;
        this.dateRange = null;
        this.dateUpRange = null;
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.getData();
        // this.message.create('success', 'Refresh the success!');
    }

    // 获取数据
    getData() {
        if (this.id === '' || this.zoneId === '' || this.roadName === '' || this.typeSelect === '' || this.statusSelect === '') {
            this.id = null;
            this.zoneId = null;
            this.roadName = null;
            this.typeSelect = null;
            this.statusSelect = null;
        }
        this.queryData = {
            condition: {
                event_ID: this.id,
                event_Type: this.typeSelect,
                planned_start_Time: {
                    startTime: this.queryStartTime,
                    endTime: this.queryEndTime
                },
                planned_end_Time: {
                    startTime: this.queryUpStartTime,
                    endTime: this.queryUpEndTime
                },
                road_Name: this.roadName,
                veri_State: this.statusSelect,
                zone_ID: this.zoneId,
                zoneIdList: this.zoneList.map(z => z.id)
            },
            pageNum: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        this.SEService.getAllList(this.queryData).subscribe(res => {
            if (res.messagecode === '000000') {
                this.listOfData = res.data.content;
                this.pagination.currentPage = res.data.pageNum;
                this.pagination.currentSize = res.data.numberOfElements;
                this.pagination.totalEle = res.data.totolElements;
                this.listOfData.forEach(element => {
                    if (element.lane_Blockage != null) {
                        const strSplit = element.lane_Blockage.split('');
                        element.laneBlockage = strSplit;
                    } else {
                        this.message.create('warning', 'Request failed.');
                        this.listOfData = [];
                    }
                });
            }
        });
    }

    addOrEdit(flag) {
        if (flag === 'add') {
            this.isEditable = false;
            this.editingItem = null;
            this.changeTabPage.emit(null);
        } else if (flag === 'edit') {
            if (this.selectedItem === null) {
                this.message.create('warning', 'Please select a record.');
            } else if (this.authService.isUserZoneChecked(this.selectedItem.zone_ID)) {
                this.selectedItem = this.listOfData.filter(item => item.eventId === this.editingItem)[0];
                this.changeTabPage.emit(this.selectedItem);
            }
        }
    }

    // 展示详情
    showDetail(item) {
        this.editingItem = item.eventId;
        this.isEditable = true;
        this.isIrSelected.emit(item);
        this.selectedItem = item;
    }

    // 点击删除
    delete() {
        // this.comfirm();
        if (this.editingItem !== null) {
            if (!this.authService.isUserZoneChecked(this.selectedItem.zone_ID)) {
                return;
            }
            // this.modal.confirm({
            //     nzTitle: '<p>Do you Want to delete record ' + this.editingItem + '?</p>',
            //     nzOnOk: () => this.message.create('success', 'Success')
            // });
            this.translate.get('Home.Home.Delete_Content').subscribe(res => {
                this.dialog
                    .confirm({
                        title: 'Home.Home.Delete_Confirm',
                        content: `${res}${this.editingItem}?`,
                        buttonOkTxt: 'UserManagement.ManageUser.Delete_Save',
                        buttonCancelTxt: 'UserManagement.ManageUser.Delete_Cancel'
                        // title: 'UserManagement.ManageUser.Delete_Role',
                        // content: 'UserManagement.ManageUser.Delete_Content',
                        // buttonOkTxt: 'UserManagement.ManageUser.Delete_Save',
                        // buttonCancelTxt: 'UserManagement.ManageUser.Delete_Cancel'
                    })
                    .subscribe(res => {
                        if (res) {
                            this.confirmDelete();
                        } else {
                        }
                    });
            });
        } else {
            this.message.create('warning', 'Please select a record.');
        }
    }

    // 确认删除
    confirmDelete(param?) {
        const header = {
            zoneId: this.zoneList
                .filter(z => !z.isTemp)
                .map(z => z.id)
                .join(','),
            isFource: param ? param : this.isCancelForce
        };
        this.SEService.cancelScheduled(this.editingItem, header).subscribe(res => {
            this.isForceCancelVisible = false;
            if (res.messagecode === '000000') {
                this.message.create('success', `Delete incident record success!`);
                this.refresh();
            } else if (res.messagecode === '900103') {
                this.isForceCancelVisible = true;
            }
        });
    }

    comfirm() {
        this.dialog
            .confirm({
                title: 'Home.Home.Delete_Confirm',
                content: '是否删除',
                buttonOkTxt: 'Save',
                buttonCancelTxt: 'Cancel'
            })
            .subscribe(res => {});
    }

    onChange(result: Date): void {
        this.queryStartTime = result[0]
            ? moment(result[0])
                  .startOf('day')
                  .valueOf()
            : null;
        this.queryEndTime = result[1]
            ? moment(result[1])
                  .endOf('day')
                  .valueOf()
            : null;
        this.getData();
    }

    onUpdateChange(result: Date): void {
        this.queryUpStartTime = result[0]
            ? moment(result[0])
                  .startOf('day')
                  .valueOf()
            : null;
        this.queryUpEndTime = result[1]
            ? moment(result[1])
                  .endOf('day')
                  .valueOf()
            : null;
        this.getData();
    }

    getTimeStamp() {
        const nowdate = new Date();
        nowdate.setMonth(nowdate.getMonth() - 3);
        const y = nowdate.getFullYear();
        const m = nowdate.getMonth() + 1;
        const d = nowdate.getDate();
        const formatwdate = y + '-' + m + '-' + d;
        return new Date(formatwdate).getTime();
    }

    onOk(result: Date): void {}

    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getData();
    }

    onSizeChange(e) {
        this.pagination.currentPage = 1;
        this.pagination.pageSize = e;
        this.getData();
    }

    typeSearch() {
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.getData();
    }

    filterSearch() {
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.getData();
    }

    statusSearch() {
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.getData();
    }

    idSearch() {
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.getData();
    }

    zoneSearch() {
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.getData();
    }
}
